<template>
  <base-page-view class-name="tab-container check-container-page" :show-to-top="false">
    <!-- #ifdef MP-WEIXIN -->
    <base-nav title="确认订单">
      <view slot="left" class="header-left" @click="handelBack">
        <image src="/static/images/icon/icon_arror_left.png" />
      </view>
    </base-nav>
    <!-- #endif -->
    <view id="wrapper" class="check-container">
      <view class="consignee">
        <view class="sLine" @click="goAddressList">
          <view v-if="!receiptAddress.address_id" class="lCont">
            <image src="/static/images/icon/icon_address.png" class="address-icon" mode="aspectFit"></image>
            <view class="address-tip">请填写收货地址</view>
          </view>
          <view v-else class="lCont addressBox">
            <image src="/static/images/icon/icon_address.png" class="address-icon" mode="aspectFit"></image>
            <view class="addressItem">
              <view class="editRow">
                <view class="p">收货人: {{ receiptAddress.name }}</view>
                <view class="b">{{ receiptAddress.region_code + ' ' + receiptAddress.mobile }}</view>
              </view>
              <view class="detail">{{ receiptAddress.province + receiptAddress.city + receiptAddress.area + receiptAddress.detail }}</view>
            </view>
          </view>
          <view class="rCont">
            <image src="/static/images/icon/icon_arror_right.png" mode="aspectFit"></image>
          </view>
        </view>
        <image v-if="!receiptAddress" src="/static/images/icon/Corrugatedline.png" style="width:100%;height: 9rpx;display:block;"></image>
      </view>
      <view class="product-all">
        <view v-if="goodsTempObj">
          <goods-item :need-role="true" :shopping-items="goodsTempObj.data.shopping_items" :prevent-click="true" @cartNumChange="cartNumChange"></goods-item>
        </view>
        <view class="product-remark">
          <view class="o-span">买家留言</view>
          <input v-model="remark" class="o-input" placeholder-class="input-placeholder" type="text" placeholder="您对本次交易的说明" />
        </view>
        <view class="sLine tax-item" @click="handleShowTax">
          <view class="lCont">发票选择</view>
          <view v-if="enable" class="rCont">
            <text v-if="taxInfo.invoiceContent === '不开发票'" class="tax-type-txt grey">{{ taxInfo.invoiceContent }}</text>
            <text v-else class="tax-type-txt">{{ taxInfo.invoiceContent }}-{{ taxInfo.invoiceTitleType }}</text>
            <image class="tax-arr-ico" src="/static/images/icon/icon_arror_right.png" mode="aspectFit"></image>
          </view>
          <view v-else class="rCont">暂不支持开发票,如有疑问，联系客服</view>
        </view>
      </view>
      <view class="price-all">
        <!-- <view v-if="couponList.length > 0 || unusable_coupon_list.length > 0" class="discount"> -->
        <view class="price-detail">
          <view class="sLine">
            <view class="lCont">
              <text class="o-span">商品金额</text>
            </view>
            <view class="rCont">
              <text v-if="goodsTempObj && goodsTempObj.data" class="o-span">¥{{ goodsTempObj.data.goods_total | formatMoney }}</text>
            </view>
          </view>
          <view class="sLine">
            <view class="lCont">
              <text class="o-span">促销活动</text>
            </view>
            <view class="rCont">
              <text v-if="goodsTempObj && goodsTempObj.data" class="o-span">-¥{{ goodsTempObj.data.discount_activity | formatMoney }}</text>
            </view>
          </view>
          <view class="sLine">
            <view class="lCont">
              <text class="o-span">会员立减</text>
            </view>
            <view class="rCont">
              <text v-if="goodsTempObj && goodsTempObj.data" class="o-span">-¥{{ goodsTempObj.data.discount_member | formatMoney }}</text>
            </view>
          </view>
          <view class="sLine">
            <view class="lCont">
              <text class="o-span">活动立减</text>
            </view>
            <view class="rCont">
              <text v-if="goodsTempObj && goodsTempObj.data" class="o-span">-¥{{ goodsTempObj.data.discount_promotion | formatMoney }}</text>
            </view>
          </view>
          <view class="sLine">
            <view class="lCont">
              <text class="o-span">优惠券</text>
            </view>
            <view v-if="couponList.length > 0" class="rCont" @click="showMask('coupon')">
              <text v-if="selectedCoupon.price" class="color-price coupon-price">-￥{{ selectedCoupon.price | formatMoney }}</text>
              <text v-else class="packet-num-show">{{ couponList.length }}张可用</text>
              <image src="/static/images/icon/icon_arror_right.png" mode="aspectFit" />
            </view>
            <view v-else class="rCont" @click="showMask('coupon')">
              <text class="disable">
                暂无可用
              </text>
            </view>
          </view>
          <view class="sLine">
            <view class="lCont">
              <text class="o-span">红包</text>
            </view>
            <view v-if="redPacketList.length" class="rCont orange" @click="showMask('redPacket')">
              <text v-if="selectedPacket.price" class="color-price red-packet-price">-￥{{ selectedPacket.price | formatMoney }}</text>
              <text v-else class="packet-num-show">{{ redPacketList.length }}张可用</text>
              <image src="/static/images/icon/icon_arror_right.png" mode="aspectFit" />
            </view>
            <view v-else class="rCont" @click="showMask('redPacket')">
              <text class="disable">
                暂无红包
              </text>
            </view>
          </view>
          <view class="sLine">
            <view class="lCont">
              <text class="o-span">邮费</text>
            </view>
            <view class="rCont">
              <text v-if="goodsTempObj && goodsTempObj.data && goodsTempObj.data.express_fee" class="o-span">¥{{ goodsTempObj.data.express_fee | formatMoney }}</text>
              <text v-else class="o-span">包邮</text>
            </view>
          </view>
          <view class="sLine">
            <view class="lCont">
              <text class="o-span">合计</text>
            </view>
            <view class="rCont">
              <text v-if="goodsTempObj && goodsTempObj.data" class="o-span">¥{{ goodsTempObj.data.total | formatMoney }}</text>
            </view>
          </view>
        </view>
      </view>
      <view class="price-all" style="margin-bottom: 40rpx;" @click="balanceClick()">
        <view class="balance">
          <view class="sLine">
            <view class="lCont">
              <text class="o-span">可用余额 {{goodsTempObj.data.available_balance | formatMoney }}</text>
            </view>
            <view class="pay-rCont">
              <url-image v-if="selectBalance" src="/static/images/member/pay/select.png" width="36" height="36"></url-image>
              <url-image v-else src="/static/images/member/pay/un-select.png" width="36" height="36"></url-image>
            </view>
          </view>
        </view>
      </view>
      <view class="bottomFix">
        <view v-if="noSupDeliveryNum >= 1 && goodsNums > 1 && noSupDeliveryNum !== goodsNums && !isBoxPackageOrder" class="orderNoDelivery">
          <!-- <image src="/static/images/icon/msg.png" alt="" class="deli-ti-icon"></image> -->
          <text class="deli-tip">温馨提示：订单中有部分商品暂不支持配送</text>
          <!--<span class="deli-tip">{{goodsTempObj.data.unsupported_area}}</span>-->
          <text class="deli-btn" @click="handleRemoveGood">点击移除</text>
        </view>
        <view v-else-if="receiptAddress && receiptAddress.province" class="orderNoDelivery">
          <text class="deli-tip">送至: {{ receiptAddress.province + receiptAddress.city + receiptAddress.area + receiptAddress.detail }}</text>
        </view>
        <view class="bottom-container">
          <view class="lPrice">
            <text class="o-b" v-if="totalPrice>0">{{ totalPrice | formatMoney }}</text>
          </view>
          <view v-if="noSupDeliveryNum == 0" class="rButton" :class="{ disable: soldOutList }" @click="showPay()">
            去付款
          </view>
          <!-- 单个商品 -->
          <view v-if="(noSupDeliveryNum == 1 && goodsNums <= 1) || (goodsNums > 1 && noSupDeliveryNum === goodsNums)" class="rButton disable">
            该地区暂不支持配送
          </view>
          <view v-else-if="noSupDeliveryNum >= 1 && goodsNums > 1" class="rButton disable">
            有商品不支持配送
          </view>
        </view>
      </view>
    </view>
    <pay-dialog ref="payDialog" :order-no="order_no" :form-type="getType" @submitCallBack="toPayResult" @close="close"></pay-dialog>
    <couponCom :show="showCoup" :coupon-list="couponList" :unusable-coupon-list="unusable_coupon_list" :selected-coupon="selectedCoupon" @close="handleSelected" @selectCoup="handleSelected" />
    <couponCom :show="showPacket" type="redPacket" :coupon-list="redPacketList" :unusable-coupon-list="[]" :selected-coupon="selectedPacket" @close="handleSelected" @selectCoup="handleSelected" />
    <!-- <redPacketCom
      :show="showPacket"
      :red-packet-list="redPacketList"
      :selected-packet="selectedPacket"
      @close="handleSelected"
      @selectPacket="handleSelected"
    /> -->
    <tax-com :show="showTax" :tax-info="taxInfo" @close="showTax = false" @deliver="getTaxData" />
    <confirm-popup ref="confirm" />
    <confirm-popup ref="groupBuyConfirm" />
    <!-- 验证码弹窗 -->
    <codePopup ref="codePopup" @again="sendCode" @close="close" @success="code=>checkCode(code)"/>
    <!-- 交易密码弹窗 -->
    <dealPassword ref="dealPassword" v-if="showDealPassword" @complete="completePassword" @close="closeDealPassword"></dealPassword>
  </base-page-view>
</template>

<script>
import './index.scss'
import { mapGetters, mapActions } from 'vuex'
import { getUserLevel } from '@/utils/common'
import payDialog from '../components/payDialog'
import dealPassword from '@/components/pay/dealPassword'
import couponCom from '../components/couponCom'
// import redPacketCom from '../components/redPacketCom'
import taxCom from '../components/taxCom'
import goodsItem from '../components/goodsItem'
import confirmPopup from '@/components/confirmPopup/index'
import { formatUrlParam, debounce } from '@/utils/tools'
import { navigateToMiniProgram, toMpHomePage, pageNavigateBack } from '@/utils/navigateTo'
import codePopup from '@/components/popup/codePopup'
export default {
  components: {
    goodsItem,
    payDialog,
    dealPassword,
    couponCom,
    // redPacketCom,
    confirmPopup,
    taxCom,
    codePopup
  },
  data() {
    return {
      soldOutList: false,
      isBoxPackageOrder: false,
      receiptAddress: {}, // 接收的地址
      remark: '', // 评论
      coupontitle: '可使用优惠券',
      couponList: [], // 优惠券列表
      unusable_coupon_list: [], // 不可使用的优惠券
      redPacketList: [], // 红包列表
      selectedCoupon: {}, // 选择的优惠券
      selectedPacket: {}, // 选择的红包
      activity_id: '',
      address_id: '', // 选择的地址id
      order_no: '',
      invite_code: '',
      showCoup: false, // 显示优惠券
      showPacket: false, // 显示红包
      is_used_coupon: 0, // 是否使用优惠券
      showTax: false, // 显示发票
      preseat: '',
      firstseat: '',
      isFirst: true,
      enable: true, // 全国发票配置开关
      taxInfo: {},
      selectBalance:true,//是否选择可用余额
      showDealPassword: false, // 显示输入交易秘密
    }
  },
  computed: {
    ...mapGetters([
      'goodsTempObj',
      'userToken',
      'extraData',
      'user'
      // 'prePageTitle',
      // 'preSeat'
    ]),
    goodsNums() {
      if (!this.goodsTempObj) return 0
      const num = this.goodsTempObj.data.shopping_items.item_list.length + this.goodsTempObj.data.shopping_items.activity_item_list.length
      return num
    },
    // 配送地区判断
    noSupDeliveryNum() {
      if (!this.goodsTempObj) return 0
      let flag = 0
      this.goodsTempObj.data.shopping_items.item_list.forEach(item => {
        if (!item.is_sup_delivery) {
          flag += 1
        }
      })
      this.goodsTempObj.data.shopping_items.activity_item_list.forEach(item => {
        if (!item.is_sup_delivery) {
          flag += 1
        }
      })
      return flag
    },
    //付款金额=订单金额-选择的可用余额
    totalPrice() {
      if (!this.goodsTempObj)return 0
      //是否选择可用余额
      if(this.selectBalance){
        let num=this.$utils.math.cut(this.goodsTempObj.data.total||0,this.goodsTempObj.data.available_balance||0);//订单金额-选择的可用余额
        return num>0?num:0;
      }else{
        return this.goodsTempObj.data.total;
      }
    },
    //需要使用的可用余额
    availableBalancePayAmt(){
      if(this.selectBalance){
        //可用余额大于订单金额时用订单金额
        return this.goodsTempObj.data.available_balance>this.goodsTempObj.data.total?this.goodsTempObj.data.total:this.goodsTempObj.data.available_balance;
      }else{
        return 0;
      }
    }
  },
  onLoad(options) {
    if (!this.userToken) {
      this.$navigateTo('/pages/login/index')
      return
    }
    if (options.bonus_gift_id) {
      this.isBoxPackageOrder = true
    }
    this.isFirst = true;
    if(this.goodsTempObj&&this.goodsTempObj.settleData){
      this.is_used_coupon = this.goodsTempObj.settleData.is_used_coupon;
    }
    if (!this.goodsTempObj) {
      if (this.extraData && this.extraData.platform) {
        toMpHomePage()
      } else {
        // #ifdef H5
        history.back()
        // #endif
        // #ifndef H5
        uni.navigateBack()
        return
        // #endif
      }
    }
  },
  onShow() {
    if (!this.goodsTempObj) {
      return
    }
    if (this.isFirst) {
      this.couponList = JSON.parse(JSON.stringify(this.goodsTempObj.data.coupon_list))
      this.unusable_coupon_list = JSON.parse(JSON.stringify(this.goodsTempObj.data.unusable_coupon_list))
      this.redPacketList = JSON.parse(JSON.stringify(this.goodsTempObj.data.hongbao_list))
      this.isFirst = false
    }

    // 清除非正常操作可能存在拼团的缓存
    uni.removeStorageSync('_group_item_info_')
    // 缓存信息给拼团用
    if (Number(JSON.parse(this.goodsTempObj.shopping_list)[0].from_type) === 25) {
      const itemInfo = this.goodsTempObj
      uni.setStorageSync('_group_item_info_', JSON.stringify(itemInfo))
    }
    const invite_code = uni.getStorageSync('share_code')
    if (invite_code) {
      this.invite_code = invite_code
    }
    // 获取选择地址回来的地址
    if (this.addressData) {
      this.address_id = this.addressData.address_id
    }

    // 评价内容
    const remark = uni.getStorageSync('__tempRemark__')

    if (remark) {
      this.remark = remark
      uni.setStorageSync('__tempRemark__', '')
    } else {
      this.remark = ''
    }
    //优惠券
    this.selectedCoupon = this.goodsTempObj.data.coupon ? this.goodsTempObj.data.coupon : {};
    //红包
    if (this.goodsTempObj.data.hongbao_list.length) {
      this.selectedPacket = this.goodsTempObj.data.hongbao ? this.goodsTempObj.data.hongbao : {}
    }
    this._getAddress()
    this.preseat = uni.getStorageSync('preseat') ? uni.getStorageSync('preseat') : ''
    this.firstseat = uni.getStorageSync('firstseat') ? uni.getStorageSync('firstseat') : ''
    this.getInvoiceSetting()
  },
  methods: {
    ...mapActions(['setGoodsTemp']),
    //可用余额点击
    balanceClick(){
      this.selectBalance=!this.selectBalance;
    },
    getType() {
      return Number(JSON.parse(this.goodsTempObj.shopping_list)[0].from_type)
    },
    // 添加订单
    async addOrder(type) {
      if (this.soldOutList) {
        return
      }
      if (this.extraData && this.extraData.data && this.extraData.data.event_liks) {
        this.$trackSDK.EVENT_LINKS = this.extraData.data.event_liks
      }
      const data = {
        preseat: this.preseat, // 页面
        firstseat: this.$trackSDK.EVENT_LINKS ? this.$trackSDK.EVENT_LINKS : this.firstseat, // 模块
        shopping_list: this.goodsTempObj.shopping_list,
        shipping_address_id: this.receiptAddress.address_id,
        remark: this.remark,
        coupon_id: this.selectedCoupon.coupon_id ? this.selectedCoupon.coupon_id : '',
        hongbao_id: this.selectedPacket.hongbao_id ? this.selectedPacket.hongbao_id : '',
        activity_id: this.activity_id,
        availableBalancePayAmt:this.availableBalancePayAmt,//选择的可用余额
      }
      // 如果有邀请码，则将邀请码一起写进去
      if (this.invite_code) {
        data.inviteCode = this.invite_code
      }
      const res = await this.$api.orderApi.orderAdd(data)
      // 5000 为拼团名额已满
      if (res.code === 5000) {
        uni.showToast({
          title: res.msg || res.message,
          icon: 'none',
          duration: 2000,
          mask: true
        })
        const groupId = JSON.parse(this.goodsTempObj.shopping_list)[0].group_id
        // 这边需要跳转
        const query = {
          group_id: groupId,
          group_full: true
        }
        const url = formatUrlParam('/pagesActivity/group-buy/result', query)
        this.$navigateTo(url)
        return
      }
      if (res.code) {
        if (res.code === 201) {
          if (res.data && res.data.skuCodeList.length > 0) {
            this.soldOutList = true
          }
          const goodsTemp = JSON.parse(JSON.stringify(this.goodsTempObj))
          const shopItem = goodsTemp.data.shopping_items
          if (shopItem.activity_item_list.length > 0) {
            shopItem.activity_item_list.forEach(item => {
              if (res.data.skuCodeList && res.data.skuCodeList.indexOf(item.sku_code) >= 0) {
                item.soldOut = true
              }
              // 如果有套餐内容
              if (item.pack) {
                const packList = item.pack.pack_list
                const presentList = item.pack.present_list
                if (packList.length) {
                  packList.forEach(i => {
                    if (res.data.skuCodeList.indexOf(i.sku_code) >= 0) {
                      i.soldOut = true
                    }
                  })
                }
                if (presentList.length) {
                  presentList.forEach(i => {
                    if (res.data.skuCodeList.indexOf(i.sku_code) >= 0) {
                      i.soldOut = true
                    }
                  })
                }
              }
            })
          }
          // 下单售罄
          if (shopItem.item_list.length > 0) {
            shopItem.item_list.forEach(item => {
              if (res.data.skuCodeList.indexOf(item.sku_code) >= 0) {
                item.soldOut = true
              }
              if (item.pack) {
                const packList = item.pack.pack_list
                const presentList = item.pack.present_list
                if (packList.length) {
                  packList.forEach(i => {
                    if (res.data.skuCodeList.indexOf(i.sku_code) >= 0) {
                      i.soldOut = true
                    }
                  })
                }
                if (presentList.length) {
                  presentList.forEach(i => {
                    if (res.data.skuCodeList.indexOf(i.sku_code) >= 0) {
                      i.soldOut = true
                    }
                  })
                }
              }
            })
          }
          this.$nextTick(() => {
            this.setGoodsTemp({
              shopping_list: goodsTemp.shopping_list,
              data: goodsTemp.data
            })
          })
        }
        return false
      }
      this.order_no = res.data.order_no
      if (this.extraData && this.extraData.data && this.extraData.data.fromSource === 'shoppingBag' && this.extraData.data.liveId && this.extraData.data.shopping_list) {
        // 删除直播购物袋的接口
        const skuList = []
        const shopping_list = JSON.parse(this.extraData.data.shopping_list)
        shopping_list.forEach(item => {
          skuList.push(item.sku_code)
        })
        if (skuList.length > 0) {
          await this.$api.orderApi.delLiveBag({
            liveId: this.extraData.data.liveId,
            skuListStr: skuList.join(',')
          })
        }
      }
      // this.$store.dispatch('setPreSeat', '')
      return true
    },
    // 去支付
    async showPay() {
      if (!this.receiptAddress || !this.receiptAddress.address_id) {
        uni.showToast({
          title: '请选择收货地址',
          icon: 'none',
          duration: 2000,
          mask: true
        })
        return
      }
      if (!/^\d{1,11}$/.test(this.receiptAddress.mobile)) {
        uni.showToast({
          title: '亲，您的收货手机号不是纯数字滴，请修改呦！',
          icon: 'none',
          duration: 2000,
          mask: true
        })
        return
      }
      if (this.taxInfo.invoiceContent !== '不开发票') {
        let msg = ''
        if (!this.taxInfo.email.trim()) {
          msg = '发票信息邮箱不能为空'
        }
        if (!this.taxInfo.invoiceTitle.trim()) {
          msg = this.taxInfo.invoiceTitleType === '单位' ? '发票信息单位名称不能为空 ' : '发票信息姓名不能为空'
        }
        if (this.taxInfo.invoiceTitleType === '单位' && !this.taxInfo.gmfTaxpayerIdentifyNo.trim()) {
          msg = '发票信息纳税人识别号不能为空'
        }
        const reg = /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
        if (!reg.test(this.taxInfo.email.trim())) {
          msg = '发票信息邮箱地址格式不正确'
        }
        if (msg) {
          uni.showToast({
            title: msg,
            icon: 'none',
            duration: 2000,
            mask: true
          })
          return
        }
      }
      // if (this.showPaying) return
      this.showPaying = true
      if (!this.order_no) {
        if (!(await this.addOrder())) {
          this.showPaying = false
          return
        }
      }

      if (this.taxInfo.invoiceContent !== '不开发票') {
        const shopping_list = JSON.parse(this.goodsTempObj.shopping_list)
        const isBox = shopping_list.findIndex(i => i.from_type * 1 === 11)
        this.taxInfo.orderNo = this.order_no
        this.taxInfo.orderType = isBox > -1 ? 11 : ''
        this.taxInfo.userId = this.user.uid
        // 申请发票
        await this.$api.invoiceApi.applyInvoice(this.taxInfo).catch(err=>{
          this.showPaying = false
        })
      }
      //需要付款的金额为0时，使用验证码弹窗，否则用支付弹窗
      if(this.totalPrice>0){
        this.$refs.payDialog.show()
      }else{
        if(this.user && this.user.trade_password_flag!==1) {
          uni.showToast({
            title: "未设置密码，请先设置",
            icon: 'none',
            duration: 2000
          })
          this.showPaying = false
          setTimeout(() => {
            this.$navigateTo("/pagesMine/dealPassword/index")
          }, 2000);
          // this.$gc.$message({
          //   content: '您暂未设置交易密码，需设置交易密码后才可以使用',
          //   title: '温馨提示',
          //   type: 'richText',
          //   showMessage: true,
          //   showCancel: true,
          //   confirmText: '立即设置',
          //   align: 'center',
          //   confirm: () => {
          //     this.$navigateTo("/pagesMine/dealPassword/index")
          //   }
          // })
          return
        }
        this.showDealPassword = true
        // this.$refs.codePopup.show();//显示验证码弹窗
        this.sendCode();//发送验证码
      }
      this.showPaying = false
    },
    async getPublicKey() {
      let res = await this.$api.mineApi.tradePasswordGetPublicKey()
      if (res.code === 0) {
        this.publicKey = res.data
      }
    },
    // 交易密码输入完成
    async completePassword(str){
      await this.getPublicKey()
       // 加密, 提交
      let jse = new this.$jsEncrypt()
      jse.setPublicKey(this.publicKey)
      let encrypted = jse.encrypt(str)
      this.checkCode(encrypted)
    },
    //发送验证码
    sendCode(){
      this.$api.orderApi.orderPay({
        pay_channel:11, // pay_channel为9时发送验证码,
        order_no: this.order_no
      }).then(res=>{
        if(res.code===0){
          // this.$msg("验证码发送成功");
          // this.$refs.codePopup.countDown();//验证码倒计时
        }
      })
    },
    //判断验证码是否正确
    checkCode(password){
      this.$api.orderApi.checkVerifyDealPassword({
        password: password, 
        order_no: this.order_no
      }).then(res=>{
        if(res.code===0){
          const fromType = Number(JSON.parse(this.goodsTempObj.shopping_list)[0].from_type)
          // 拼单的转跳
          if (fromType === 25) {
            let miniUrl = ''
            if (JSON.parse(this.goodsTempObj.shopping_list)[0].group_id) {
              // 参团
              miniUrl = '/pagesActivity/group-buy/result?group_id=' + Number(JSON.parse(this.goodsTempObj.shopping_list)[0].group_id)
            } else {
              // 开团
              miniUrl = '/pagesActivity/group-buy/result?group_id=&order_no=' + this.order_no
            }
            this.$store.dispatch('setGoodsTemp', null)
            this.$navigateTo(miniUrl, '', 'redirectTo')
          } else {
            this.$store.dispatch('setGoodsTemp', null)
            this.$navigateTo('/pagesOrder/orderSuccess/index?orderNo=' + this.order_no, '', 'redirectTo')
          }
        }
      }).catch((err)=>{
        // 1000002
        if(err.code === 1000002){
          this.showDealPassword = false
          this.$gc.$message({
            content: '超过6次错误, 交易密码已锁定, 请重置可解锁交易密码',
            title: '温馨提示',
            type: 'richText',
            showMessage: true,
            showCancel: true,
            confirmText: '重置交易密码',
            align: 'center',
            confirm: () => {
              this.$navigateTo("/pagesMine/dealPassword/index?status=1")
            }
          })
        }else{
          // 清除密码
          this.$refs.dealPassword.clearPassword()
          uni.showToast({
            title: err.msg,
            icon: 'none',
            duration: 3 * 1000
          })
        }
      });
    },
    // 支付结果
    toPayResult(data) {
      // #ifdef H5
      const type = data.type
      if (type === '2') {
        // h5支付
        let wechatUrl = data.url
        const fromType = Number(JSON.parse(this.goodsTempObj.shopping_list)[0].from_type)
        if (fromType === 25) {
          // 如果是参团
          if (JSON.parse(this.goodsTempObj.shopping_list)[0].group_id) {
            wechatUrl += `&redirect_url=${encodeURIComponent(
              location.origin + '/pagesActivity/group-buy/result?group_id=' + Number(JSON.parse(this.goodsTempObj.shopping_list)[0].group_id) + '&order_no=' + this.order_no
            )}`
          } else {
            // 开团
            wechatUrl += `&redirect_url=${encodeURIComponent(location.origin + '/pagesActivity/group-buy/result?group_id=&order_no=' + this.order_no)}`
          }
        } else {
          wechatUrl += `&redirect_url=${encodeURIComponent(location.origin + '/pagesOrder/orderSuccess/index?orderNo=' + this.order_no)}`
        }
        location.href = wechatUrl
      }
      // #endif
      // #ifdef MP-WEIXIN
      const fromType = Number(JSON.parse(this.goodsTempObj.shopping_list)[0].from_type)
      // 拼单的转跳
      if (fromType === 25) {
        let miniUrl = ''
        if (JSON.parse(this.goodsTempObj.shopping_list)[0].group_id) {
          // 参团
          miniUrl = '/pagesActivity/group-buy/result?group_id=' + Number(JSON.parse(this.goodsTempObj.shopping_list)[0].group_id)
        } else {
          // 开团
          miniUrl = '/pagesActivity/group-buy/result?group_id=&order_no=' + this.order_no
        }
        this.$store.dispatch('setGoodsTemp', null)
        this.$navigateTo(miniUrl, '', 'redirectTo')
      } else {
        this.$store.dispatch('setGoodsTemp', null)
        this.$navigateTo('/pagesOrder/orderSuccess/index?orderNo=' + this.order_no, '', 'redirectTo')
      }
      // #endif
    },
    // 未支付跳转到订单详情
    close() {
      this.$navigateTo('/pagesOrder/orderDetail/index?orderNo=' + this.order_no, '', 'redirectTo')
    },
    closeDealPassword() {
      this.showDealPassword = false
      this.close()
    },
    // 点击移除商品
    handleRemoveGood() {
      this.$refs.confirm.show({
        title: '温馨提示',
        content: '订单中有' + this.noSupDeliveryNum + '件商品暂不支持配送，确定删除才能正常下单',
        yesTxt: '确认',
        yesCb: () => {
          this.removeNoSupShop()
        }
      })
    },
    // 确定移除不支持配送的
    async removeNoSupShop() {
      const newList = this.goodsTempObj.data.shopping_items.item_list.filter(item => item.is_sup_delivery)
      const AnewList = this.goodsTempObj.data.shopping_items.activity_item_list.filter(item => item.is_sup_delivery)

      const res = {
        item_list: newList,
        activity_item_list: AnewList
      }
      // 做了移除以后的数量小于0 则直接返回上一页
      if (newList.length + AnewList.length <= 0) {
        this.handelBack()
        return
      }
      // 重新设置vuex的换乘

      const newGoodsTempObj = JSON.parse(JSON.stringify(this.goodsTempObj))
      newGoodsTempObj.data.shopping_items = res
      this.setGoodsTemp(newGoodsTempObj)

      const idList = []
      newList.forEach(item => {
        if (item.goods_id) {
          idList.push(item.goods_id)
        } else {
          idList.push(item.package_id)
        }
      })
      AnewList.forEach(item => {
        if (item.goods_id) {
          idList.push(item.goods_id)
        } else {
          idList.push(item.package_id)
        }
      })

      const shoppingListNew = []
      JSON.parse(this.goodsTempObj.shopping_list).map(item => {
        idList.map(i => {
          if (item.goods_id.indexOf(i) >= 0) {
            shoppingListNew.push(item)
          }
        })
      })
      const settleRes = await this.$api.orderApi.orderSettle({
        // is_used_coupon: this.couponList.length ? 1 : 0,
        coupon_id: this.selectedCoupon && this.selectedCoupon.coupon_id ? this.selectedCoupon.coupon_id : '',
        hongbao_id: this.selectedPacket && this.selectedPacket.hongbao_id ? this.selectedPacket.hongbao_id : '',
        is_used_coupon: this.is_used_coupon,
        shopping_list: JSON.stringify(shoppingListNew),
        shipping_address_id: this.receiptAddress.address_id
      })
      // 重新设置商品
      this.setGoodsTemp({
        shopping_list: JSON.stringify(shoppingListNew),
        data: settleRes.data
      })
    },
    // 显示弹窗
    showMask(type, limit) {
      switch (type) {
        case 'coupon':
          if (this.couponList.length > 0) {
            this.showCoup = true
          }

          break
        case 'redPacket':
          if (this.redPacketList.length > 0) {
            this.showPacket = true
          }
          break
        default:
          break
      }
    },
    // 红包，优惠券弹窗回调
    async handleSelected(data) {
      if (data.isClose) {
        this.showCoup = false
        this.showPacket = false
        return
      }
      const item = data.item
      if (data.type === 'redPacket') {
        this.selectedPacket = item
      } else if (data.type === 'coupon') {
        this.selectedCoupon = item
        this.is_used_coupon = this.selectedCoupon && this.selectedCoupon.coupon_id && data.type === 'coupon' ? 1 : 0
      }
      if (data.type) {
        this.reSettle()
      }
      this.showCoup = false
      this.showPacket = false
    },
    // 重新结算
    async reSettle(changeCoupon) {
      const newData = {
        is_used_coupon: this.is_used_coupon,
        coupon_id: this.is_used_coupon && this.selectedCoupon && this.selectedCoupon.coupon_id ? this.selectedCoupon.coupon_id : '',
        hongbao_id: this.selectedPacket && this.selectedPacket.hongbao_id ? this.selectedPacket.hongbao_id : '',
        shipping_address_id: this.receiptAddress && this.receiptAddress.address_id ? this.receiptAddress.address_id : '',
        shopping_list: this.goodsTempObj.shopping_list
      }
      const res = await this.$api.orderApi.orderSettle(newData)
      if (res.success) {
        this.setGoodsTemp({
          shopping_list: this.goodsTempObj.shopping_list,
          data: res.data
        })
        this.couponList = JSON.parse(JSON.stringify(res.data.coupon_list))
        this.unusable_coupon_list = JSON.parse(JSON.stringify(res.data.unusable_coupon_list))
        this.selectedCoupon = res.data.coupon ? res.data.coupon : {}
      }
    },
    // 获取地址
    async _getAddress() {
      if (!this.address_id) {
        const res = await this.$api.mineApi.getShippingAddressList()
        // 没有选中送货地址，但是查询列表有地址
        if (res.data && res.data.length > 0) {
          this.receiptAddress = this.goodsTempObj.data.shipping_address
        } else {
          this.receiptAddress = null
        }
        // 如果没有地址则弹窗提示添加
        if (!this.receiptAddress) {
          this.$refs.confirm.show({
            title: '温馨提示',
            cancelTxt: '取消',
            yesTxt: '添加',
            content: '您还没有收货地址，请点击添加',
            yesCb: () => {
              this.goAddressList()
            }
          })
        }
        return
      }
      // 获取新地址以后，重新请求运费配送
      const res = await this.$api.mineApi.getShippingAddressList()
      res.data.forEach(element => {
        if (element.address_id === this.address_id) {
          this.receiptAddress = element
        }
      })
      // 重新设置数据
      this.reSettle()
    },
    // 订单数量修改
    cartNumChange: debounce(function(e) {
      try {
        const temp = JSON.parse(this.goodsTempObj.shopping_list)
        if (e.item.type === 2 && e.item.pack && e.item.pack.pack_list) {
          var packId = ''
          e.item.pack.pack_list.forEach(item => {
            packId += `_${item.sku_code}`
          })
        }
        temp.forEach(el => {
          if (e.item.type === 2) {
            let elPackId = ''
            el.pack_list.forEach(item => {
              elPackId += `_${item.sku_code}`
            })
            if (elPackId === packId) {
              el.num = e.nums
            }
          } else if (el.goods_id === e.item.goods_id && el.sku_code === e.item.sku_code) {
            el.num = e.nums
          }
        })
        this.goodsTempObj.shopping_list = JSON.stringify(temp)
      } catch (error) {
        console.log('cartNumChange error', error)
      }
      this.reSettle()
    }, 500),
    // 用户信息等级
    _getUserLevel(id) {
      return getUserLevel(id)
    },
    // 跳转到地址选项
    goAddressList() {
      uni.setStorageSync('__tempRemark__', this.remark)
      this.$navigateTo('/pagesMine/address/address?type=select')
    },
    // 返回
    handelBack() {
      if (this.extraData && this.extraData.platform) {
        navigateToMiniProgram({
          success: () => {
            toMpHomePage()
            this.$store.dispatch('setExtraData', null)
            this.$store.dispatch('setGoodsTemp', null)
          }
        })
      } else {
        pageNavigateBack()
      }
    },
    // 获取发票配置开关
    async getInvoiceSetting() {
      const res = await this.$api.invoiceApi.getInvoiceSetting()
      if (res.success) {
        this.enable = res.data.enable
      }
    },
    // 显示发票弹窗
    handleShowTax() {
      if (this.enable) {
        this.showTax = true
      }
    },
    // 获取数据
    getTaxData(data) {
      this.taxInfo = data
    }
  },
  onBackPress(options) {
    if (options.from === 'navigateBack') {
      return false
    }
    if (!this.goodsTempObj) {
      uni.navigateBack()
      return
    }
    if (Number(JSON.parse(this.goodsTempObj.shopping_list)[0].from_type) === 25) {
      this.$refs.groupBuyConfirm.show({
        title: '确定要放弃付款吗',
        content: '你尚未完成支付，喜欢的商品 可能会被抢空哦~',
        yesCb: () => {
          uni.navigateBack()
        }
      })
    }
  }
}
</script>
